﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;

namespace WPF.CustomControl
{
    public class HLEditTextBox : TextBox
    {
        public HLEditTextBox()
        {
            
        }

        protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
        {
            base.OnLostFocus(e);
        }

        #region 属性
        private EditType _EditType;
        /// <summary>
        /// 输入类型
        /// </summary>
        public EditType EditType
        {
            get { return _EditType; }
            set { _EditType = value; }
        }
        #endregion

        #region 改变事件
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            string strRex = null;
            if (_EditType == EditType.Integer)
                strRex = @"^[0-9]+$";
            if (_EditType == EditType.Letter)
                strRex = @"^[a-zA-Z]+$";
            if (_EditType == EditType.UpperLetter)
                strRex = @"^[A-Z]+$";
            if (_EditType == EditType.LowerLetter)
                strRex = @"^[a-z]+$";
            if (_EditType == EditType.Decimal)
                strRex = @"^[0-9]+(.[0-9]{0,})?$";
            if (_EditType == EditType.Chinese)
                strRex = @"[\u4e00-\u9fa5]";
            Verification(e, strRex);
        }

        #region 文本框类型
        private void Verification(TextChangedEventArgs e, string strRex)
        {
            if (strRex == null) return;
            TextBox textBox = this;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);
            int offset = change[0].Offset;

            if (change[0].AddedLength > 0)
            {
                bool b = System.Text.RegularExpressions.Regex.IsMatch(textBox.Text, strRex);
                if (!b)
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }
        }
        #endregion
        #endregion


    }
}
public enum EditType
{
    /// <summary>
    /// 默认所有
    /// </summary>
    Default,
    /// <summary>
    /// 整数
    /// </summary>
    Integer,
    /// <summary>
    /// 字母
    /// </summary>
    Letter,
    /// <summary>
    /// 大写字母
    /// </summary>
    UpperLetter,
    /// <summary>
    /// 小写字母
    /// </summary>
    LowerLetter,
    /// <summary>
    /// 小数
    /// </summary>
    Decimal,
    /// <summary>
    /// 汉字
    /// </summary>
    Chinese,

}

